import React from 'react';
import styles from './img-area.scss';
import ImgRepo from 'components/ImgRepo';
import {Icon} from 'antd';
import {IMG_DOMAIN} from 'utils/constants';

class ImgArea extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      url: this.props.imgUrl
        ? `${IMG_DOMAIN}${this.props.imgUrl}`
        : 'https://liuliu-game-box.oss-cn-shenzhen.aliyuncs.com/img/default.jpeg',
      visible: false
    };
  }

  onUpload() {
    this.setState({
      visible: true
    });
  }

  onClose() {
    this.setState({
      visible: false
    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.imgUrl !== nextProps.imgUrl && nextProps.imgUrl) {
      this.setState({
        url: `${IMG_DOMAIN}${nextProps.imgUrl}`
      });
    }
  }

  onImgChange(url) {
    this.setState({
      url: `${IMG_DOMAIN}${url}`
    });
    this.props.onChange && this.props.onChange(url);
  }

  render() {
    return (
      <div className={styles.wrap}>
        <div className={styles.label}>{this.props.label}</div>
        <div className={styles.imgWrap}>
          <img className={styles.preview} src={this.state.url} />
          <div
            className={styles.mock}
            onClick={() => {
              this.onUpload();
            }}
            role="presentation"
          >
            <Icon type="upload" theme="outlined" style={{fontSize: '36px'}} />
          </div>
        </div>
        <ImgRepo
          visible={this.state.visible}
          btnId={this.props.btnId}
          onClose={() => {
            this.onClose();
          }}
          onChange={(url) => {
            this.onImgChange(url);
          }}
        />
      </div>
    );
  }
}

export default ImgArea;
